package org.jash.learnmvp.chat;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.hyphenate.chat.EMConversation;


import org.jash.learnmvp.R;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ConversationAdapter extends RecyclerView.Adapter<ConversationAdapter.ContactViewHolder> {
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private List<EMConversation> data = new ArrayList<>();
    private MyListener listener;
    @NonNull
    @Override
    public ContactViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ContactViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_conversation, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ContactViewHolder holder, int position) {
        EMConversation contact = data.get(position);
        holder.username.setText(contact.conversationId());
        holder.time.setText(sdf.format(new Date(contact.getLastMessage().getMsgTime())));
        Glide.with(holder.icon)
                .load("http://gips2.baidu.com/it/u=195724436,3554684702&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960")
                .transform(new CircleCrop())
                .into(holder.icon);
        if (listener != null) {
            holder.itemView.setOnClickListener(v -> listener.onItemClick(contact));
        }
    }

    @Override
    public int getItemCount() {
        return data.size();
    }

    public void setListener(MyListener listener) {
        this.listener = listener;
    }
    public void addAll(List<EMConversation> list) {
        int size = data.size();
        data.addAll(list);
        notifyItemRangeInserted(size, list.size());
    }

    public interface MyListener {
        void onItemClick(EMConversation contact);
    }
    public static class ContactViewHolder extends RecyclerView.ViewHolder {
        private ImageView icon;
        private TextView username;
        private TextView time;
        public ContactViewHolder(@NonNull View itemView) {
            super(itemView);
            icon = itemView.findViewById(R.id.icon);
            username = itemView.findViewById(R.id.username);
            time = itemView.findViewById(R.id.time);
        }
    }
}
